package com.clothing.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.number.NumberFormatter;

/**
 * @ClassName: Utils
 * @Description: TODO(Utils - 工具类)
 * @author Charles.Tao
 * @date 2016年3月28日 上午11:09:21
 * @version 1.0
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Utils
{
    public static final Logger log = LoggerFactory.getLogger(Utils.class);

    public static final String[] defaultIllegalFile = { "jpg", "png", "jpeg",
            "bmp", "zip", "gz", "tar", "xls", "xlsx", "doc", "docx" };

    public static final String[] defaultIllegalPicFile = { "jpg", "png", "jpeg",
            "bmp", "gif" };

    private static final int[] secPosValueList = { 1601, 1637, 1833, 2078, 2274,
            2302, 2433, 2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858,
            4027, 4086, 4390, 4558, 4684, 4925, 5249, 5600 };

    private static final char[] firstLetter = { 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
            'w', 'x', 'y', 'z' };

    private static String[] illegalKeys = { "[but", "be", "with", "such",
            "then", "for", "no", "will", "not", "are", "and", "their", "if",
            "this", "on", "into", "a", "or", "there", "in", "that", "they",
            "was", "is", "it", "an", "the", "as", "at", "these", "by", "to",
            "of]" };

    public static boolean isNotZero(Integer number)
    {
        return number != null && number.intValue() != 0;
    }

    public static boolean isPositiveShort(Short number)
    {
        return number != null && number.shortValue() > 0;
    }

    public static boolean isPositiveInteger(Integer number)
    {
        return number != null && number.intValue() > 0;
    }

    public static boolean isPositiveLong(Long number)
    {
        return number != null && number.longValue() > 0l;
    }

    public static boolean isTrue(Boolean b)
    {
        return b != null && b.booleanValue();
    }

    public static boolean checkFloat(String num, String type)
    {
        String eL = "";
        if (type.equals("0+"))
            eL = "^\\d+(\\.\\d+)?$";
        else if (type.equals("+"))
            eL = "^((\\d+\\.\\d*[1-9]\\d*)|(\\d*[1-9]\\d*\\.\\d+)|(\\d*[1-9]\\d*))$";
        else if (type.equals("-0"))
            eL = "^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$";
        else if (type.equals("-"))
            eL = "^(-((\\d+\\.\\d*[1-9]\\d*)|(\\d*[1-9]\\d*\\.\\d+)|(\\d*[1-9]\\d*)))$";
        else
            eL = "^(-?\\d+)(\\.\\d+)?$";
        Pattern p = Pattern.compile(eL);
        Matcher m = p.matcher(num);
        return m.matches();
    }

    public static boolean isInArray(String value, String[] array)
    {
        if (array == null)
            return false;
        for (String v : array)
            if (v.equals(value))
                return true;
        return false;
    }

    public static boolean isInArray(int value, String[] array)
    {
        if (array == null)
            return false;
        for (String v : array)
            if (Integer.valueOf(v).intValue() == value)
                return true;
        return false;
    }

    public static boolean isInArrayIgnoreCase(String value, String[] array)
    {
        if (array == null)
            return false;
        for (String v : array)
            if (v.equalsIgnoreCase(value))
                return true;
        return false;
    }

    public static int findFromList(Object value, List list)
    {
        if (list == null)
            return -1;
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i).equals(value))
                return i;
        }
        return -1;
    }

    public static String implode(String str, Object[] array)
    {
        if ((str == null) || (array == null))
        {
            return "";
        }
        String result = "";
        for (int i = 0; i < array.length; i++)
        {
            if (i == array.length - 1)
                result = result + array[i].toString();
            else
            {
                result = result + array[i].toString() + str;
            }
        }
        return result;
    }

    public static String md5(String str)
    {
        MessageDigest messageDigest = null;
        try
        {
            messageDigest = MessageDigest.getInstance("MD5");
        }
        catch(NoSuchAlgorithmException ex)
        {
            ex.printStackTrace();
            return null;
        }
        byte[] resultByte = messageDigest.digest(str.getBytes());
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < resultByte.length; i++)
        {
            result.append(Integer.toHexString(0xFF & resultByte[i]));
        }
        return result.toString();
    }

    public static boolean validEmail(String sEmail)
    {
        if (StringUtils.isEmpty(sEmail))
            return false;
        String pattern = "^([a-z0-9A-Z]+[-|\\.|_]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        return sEmail.matches(pattern);
    }

    public static boolean validMaxLen(String str, int length)
    {
        if ((str == null) || (str.equals("")))
        {
            return false;
        }
        if (str.length() > length)
        {
            return false;
        }
        return true;
    }

    public static boolean validMinLen(String str, int length)
    {
        if ((str == null) || (str.equals("")))
        {
            return false;
        }
        if (str.length() < length)
        {
            return false;
        }
        return true;
    }

    public static boolean isEmpty(String str)
    {
        if ((str == null) || ("".equals(str)))
        {
            return true;
        }
        String pattern = "\\S";
        Pattern p = Pattern.compile(pattern, 34);
        Matcher m = p.matcher(str);
        return !m.find();
    }

    public static boolean isEmpty(Collection<?> col)
    {
        if ((null == col) || (col.isEmpty()))
        {
            return true;
        }
        return false;
    }

    public static boolean isEmpty(Map<?, ?> map)
    {
        if ((null == map) || (map.isEmpty()))
        {
            return true;
        }

        return false;
    }

    /**
     * 判断指定的对象数组是否为空
     *
     * @param objArr
     *            对象数组
     * @return [参数说明]
     *
     * @return boolean [返回类型说明]
     * @exception throws
     *                [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static boolean isEmpty(Object[] objArr)
    {
        if ((null == objArr) || (objArr.length < 1))
        {
            return true;
        }
        return false;
    }

    public static boolean equals(String str1, String str2)
    {
        if ((str1 == null) || (str1.equals("")) || (str2 == null)
                || (str2.equals("")))
        {
            return false;
        }
        return str1.equals(str2);
    }

    public static short toShort(String str)
    {
        if ((str == null) || (str.equals("")))
            return 0;

        try
        {
            return Short.parseShort(str);
        }
        catch(Exception ex)
        {
            return 0;
        }
    }

    public static int toInt(String str, boolean checked)
    {
        int value = 0;
        if ((str == null) || (str.equals("")))
            return 0;
        try
        {
            value = Integer.parseInt(str);
        }
        catch(Exception ex)
        {
            if (checked)
            {
                throw new RuntimeException("整型数字格式不正确");
            }
            return 0;
        }

        return value;
    }

    public static long toLong(String str)
    {
        if ((str == null) || (str.equals("")))
            return 0l;

        try
        {
            return Long.parseLong(str);
        }
        catch(Exception ex)
        {
            return 0l;
        }
    }

    public static Double toDouble(String str, boolean checked)
    {
        Double value = Double.valueOf(0.0D);
        if ((str == null) || (str.equals("")))
            return Double.valueOf(0.0D);
        try
        {
            value = Double.valueOf(str);
        }
        catch(Exception ex)
        {
            if (checked)
            {
                throw new RuntimeException("数字格式不正确");
            }
            return Double.valueOf(0.0D);
        }
        return value;
    }

    public static String formatDouble(double d)
    {
        return new DecimalFormat("#.00").format(d);
    }

    public static String fomatDoubleFraction(double number, int fractionDigits)
    {
        NumberFormat ddf1 = NumberFormat.getNumberInstance();
        ddf1.setMaximumFractionDigits(fractionDigits);
        return ddf1.format(number);
    }

    // TODO
    public static String arrayToString(Object[] array, String split)
    {
        if (array == null)
        {
            return "";
        }
        String str = "";
        for (int i = 0; i < array.length; i++)
        {
            if (i != array.length - 1)
                str = str + array[i].toString() + split;
            else
            {
                str = str + array[i].toString();
            }
        }
        return str;
    }

    public static String listToString(List list, String split)
    {
        if ((list == null) || (list.isEmpty()))
            return "";
        StringBuffer sb = new StringBuffer();
        for (Iterator localIterator = list.iterator(); localIterator.hasNext();)
        {
            Object obj = localIterator.next();
            if (sb.length() != 0)
            {
                sb.append(split);
            }
            sb.append(obj.toString());
        }
        return sb.toString();
    }

    public static String getWebInfPath()
    {
        String filePath = Thread.currentThread().getContextClassLoader()
                .getResource("").toString();
        if (filePath.toLowerCase().indexOf("file:") > -1)
        {
            filePath = filePath.substring(6, filePath.length());
        }
        if (filePath.toLowerCase().indexOf("classes") > -1)
        {
            filePath = filePath.replaceAll("/classes", "");
        }
        if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0)
        {
            filePath = "/" + filePath;
        }
        if (!filePath.endsWith("/"))
            filePath = filePath + "/";
        return filePath;
    }

    public static String getRootPath()
    {
        String filePath = Thread.currentThread().getContextClassLoader()
                .getResource("").toString();
        if (filePath.toLowerCase().indexOf("file:") > -1)
        {
            filePath = filePath.substring(6, filePath.length());
        }
        if (filePath.toLowerCase().indexOf("classes") > -1)
        {
            filePath = filePath.replaceAll("/classes", "");
        }
        if (filePath.toLowerCase().indexOf("web-inf") > -1)
        {
            filePath = filePath.substring(0, filePath.length() - 9);
        }
        if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0)
        {
            filePath = "/" + filePath;
        }

        if (filePath.endsWith("/"))
        {
            filePath = filePath.substring(0, filePath.length() - 1);
        }
        return filePath;
    }

    public static String getRootPath(String resource)
    {
        String filePath = Thread.currentThread().getContextClassLoader()
                .getResource(resource).toString();
        if (filePath.toLowerCase().indexOf("file:") > -1)
        {
            filePath = filePath.substring(6, filePath.length());
        }

        if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0)
        {
            filePath = "/" + filePath;
        }
        if (!filePath.endsWith("/"))
        {
            filePath = filePath + "/";
        }
        return filePath;
    }

    public static int formatPage(String page)
    {
        int iPage = 1;
        if ((page == null) || (page.equals("")))
            return iPage;
        try
        {
            iPage = Integer.parseInt(page);
        }
        catch(Exception ex)
        {
            iPage = 1;
        }
        return iPage;
    }

    public static String getFileSize(String fileSize)
    {
        String temp = "";
        DecimalFormat df = new DecimalFormat("0.00");
        double dbFileSize = Double.parseDouble(fileSize);
        if (dbFileSize >= 1024.0D)
        {
            if (dbFileSize >= 1048576.0D)
            {
                if (dbFileSize >= 1073741824.0D)
                    temp = df.format(dbFileSize / 1024.0D / 1024.0D / 1024.0D)
                            + " GB";
                else
                    temp = df.format(dbFileSize / 1024.0D / 1024.0D) + " MB";
            }
            else
                temp = df.format(dbFileSize / 1024.0D) + " KB";
        }
        else
        {
            temp = df.format(dbFileSize / 1024.0D) + " KB";
        }
        return temp;
    }

    public static String getEntry()
    {
        Random random = new Random(100L);
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(
                new String("yyyyMMddHHmmssS"));
        return md5(formatter.format(now) + random.nextDouble());
    }

    public static String toUTF8(String str)
    {
        if ((str == null) || (str.equals("")))
            return "";
        try
        {
            return new String(str.getBytes("ISO8859-1"), "UTF-8");
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return "";
    }

    public static String to(String str, String charset)
    {
        if ((str == null) || (str.equals("")))
            return "";
        try
        {
            return new String(str.getBytes("ISO8859-1"), charset);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return "";
    }

    public static String getRandStr(int n)
    {
        Random random = new Random();
        String sRand = "";
        for (int i = 0; i < n; i++)
        {
            String rand = String.valueOf(random.nextInt(10));
            sRand = sRand + rand;
        }
        return sRand;
    }

    public static String getChineseNum(int num)
    {
        String[] chineseNum = { "一", "二", "三", "四", "五", "六", "七", "八", "九",
                "十" };
        return chineseNum[num];
    }

    public static String replaceAll(String source, String target,
            String content)
    {
        StringBuffer buffer = new StringBuffer(source);
        int start = buffer.indexOf(target);
        if (start > 0)
        {
            source = buffer.replace(start, start + target.length(), content)
                    .toString();
        }
        return source;
    }

    public static String getTxtWithoutHTMLElement(String element)
    {
        if ((element == null) || ("".equals(element.trim())))
        {
            return element;
        }

        Pattern pattern = Pattern.compile("<[^<|^>]*>");
        Matcher matcher = pattern.matcher(element);
        StringBuffer txt = new StringBuffer();
        while (matcher.find())
        {
            String group = matcher.group();
            if (group.matches("<[\\s]*>"))
                matcher.appendReplacement(txt, group);
            else
            {
                matcher.appendReplacement(txt, "");
            }
        }
        matcher.appendTail(txt);
        String temp = txt.toString().replaceAll("\n", "");
        temp = temp.replaceAll(" ", "");
        return temp;
    }

    public static String toTrim(String strtrim)
    {
        if ((strtrim != null) && (!strtrim.equals("")))
        {
            return strtrim.trim();
        }
        return "";
    }

    public static String filterDollarStr(String str)
    {
        String sReturn = "";
        if (!toTrim(str).equals(""))
        {
            if (str.indexOf('$', 0) > -1)
            {
                while (str.length() > 0)
                {
                    if (str.indexOf('$', 0) > -1)
                    {
                        sReturn = sReturn
                                + str.subSequence(0, str.indexOf('$', 0));
                        sReturn = sReturn + "\\$";
                        str = str.substring(str.indexOf('$', 0) + 1,
                                str.length());
                    }
                    else
                    {
                        sReturn = sReturn + str;
                        str = "";
                    }
                }
            }
            else
            {
                sReturn = str;
            }
        }
        return sReturn;
    }

    public static String compressHtml(String html)
    {
        if (html == null)
        {
            return null;
        }
        html = html.replaceAll("[\\t\\n\\f\\r]", "");
        return html;
    }

    public static String toCurrency(Double d)
    {
        if (d != null)
        {
            DecimalFormat df = new DecimalFormat("￥#,###.00");
            return df.format(d);
        }
        return "";
    }

    public static String toString(Integer i)
    {
        if (i != null)
        {
            return String.valueOf(i);
        }
        return "";
    }

    public static String toString(Double d)
    {
        if (d != null)
        {
            return String.valueOf(d);
        }
        return "";
    }

    public static String getRandomNumberCode(int length)
    {
        int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Random rand = new Random();
        for (int i = 10; i > 1; i--)
        {
            int index = rand.nextInt(i);
            int tmp = array[index];
            array[index] = array[(i - 1)];
            array[(i - 1)] = tmp;
        }
        int result = 0;
        for (int i = 0; i < length; i++)
        {
            result = result * 10 + array[i];
        }
        return String.valueOf(result);
    }

    public static int getMaxLevelCode(int code)
    {
        String codeStr = String.valueOf(code);
        StringBuffer str = new StringBuffer();
        boolean flag = true;
        for (int i = codeStr.length() - 1; i >= 0; i--)
        {
            char c = codeStr.charAt(i);
            if ((c == '0') && (flag))
            {
                str.insert(0, '9');
            }
            else
            {
                str.insert(0, c);
                flag = false;
            }
        }
        return Integer.valueOf(str.toString()).intValue();
    }

    public static String delSqlComment(String content)
    {
        String pattern = "/\\*(.|[\r\n])*?\\*/";
        Pattern p = Pattern.compile(pattern, 34);
        Matcher m = p.matcher(content);
        if (m.find())
        {
            content = m.replaceAll("");
        }
        return content;
    }

    public static String inputStream2String(InputStream is)
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try
        {
            while ((line = in.readLine()) != null)
                buffer.append(line);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static String decode(String keyword)
    {
        try
        {
            keyword = URLDecoder.decode(keyword, "UTF-8");
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return keyword;
    }

    public static String doFilter(String regex, String rpstr, String source)
    {
        Pattern p = Pattern.compile(regex, 34);
        Matcher m = p.matcher(source);
        return m.replaceAll(rpstr);
    }

    public static String formatScript(String source)
    {
        source = source.replaceAll("javascript", "&#106avascript");
        source = source.replaceAll("jscript:", "&#106script:");
        source = source.replaceAll("js:", "&#106s:");
        source = source.replaceAll("value", "&#118alue");
        source = source.replaceAll("about:", "about&#58");
        source = source.replaceAll("file:", "file&#58");
        source = source.replaceAll("document.cookie", "documents&#46cookie");
        source = source.replaceAll("vbscript:", "&#118bscript:");
        source = source.replaceAll("vbs:", "&#118bs:");
        source = doFilter("(on(mouse|exit|error|click|key))", "&#111n$2",
                source);
        return source;
    }

    public static String htmlDecode(String htmlContent)
    {
        htmlContent = formatScript(htmlContent);
        htmlContent = htmlContent.replaceAll(" ", "&nbsp;")
                .replaceAll("<", "&lt;").replaceAll(">", "&gt;")
                .replaceAll("\n\r", "<br>").replaceAll("\r\n", "<br>")
                .replaceAll("\r", "<br>");
        return htmlContent;
    }

    public static String iso88591ToUtf8(String iso88591)
    {
        String s = "";
        try
        {
            s = new String(iso88591.getBytes("ISO-8859-1"), "UTF-8");
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return s;
    }

    public static boolean hasCn(String s)
    {
        if (s == null)
            return false;
        return countCn(s) > s.length();
    }

    public static int countCn(String s)
    {
        if (s == null)
        {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < s.length(); i++)
        {
            if (s.codePointAt(i) < 256)
                count++;
            else
            {
                count += 2;
            }
        }
        return count;
    }

    public static String txt2htm(String txt)
    {
        if (StringUtils.isBlank(txt))
        {
            return txt;
        }
        StringBuilder bld = new StringBuilder();

        for (int i = 0; i < txt.length(); i++)
        {
            char c = txt.charAt(i);
            switch (c)
            {
            case '&':
                bld.append("&amp;");
                break;
            case '<':
                bld.append("&lt;");
                break;
            case '>':
                bld.append("&gt;");
                break;
            case '"':
                bld.append("&quot;");
                break;
            case ' ':
                bld.append("&nbsp;");
                break;
            case '\n':
                bld.append("<br/>");
                break;
            default:
                bld.append(c);
            }
        }

        return bld.toString();
    }

    public static String htm2txt(String htm)
    {
        if (htm == null)
            return htm;
        htm = htm.replace("&amp;", "&");
        htm = htm.replace("&lt;", "<");
        htm = htm.replace("&gt;", ">");
        htm = htm.replace("&quot;", "\"");
        htm = htm.replace("&nbsp;", " ");
        htm = htm.replace("<br/>", "\n");
        return htm;
    }

    public String Q2B(String qjStr)
    {
        String outStr = "";
        String Tstr = "";
        byte[] b = (byte[]) null;
        for (int i = 0; i < qjStr.length(); i++)
        {
            try
            {
                Tstr = qjStr.substring(i, i + 1);
                b = Tstr.getBytes("unicode");
            }
            catch(UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }
            if (b[3] == -1)
            {
                b[2] = ((byte) (b[2] + 32));
                b[3] = 0;
                try
                {
                    outStr = outStr + new String(b, "unicode");
                }
                catch(UnsupportedEncodingException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                outStr = outStr + Tstr;
            }
        }
        return outStr;
    }

    public static String getFirstLetter(String oriStr)
    {
        String str = oriStr.toLowerCase();
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            char[] temp = { ch };
            byte[] uniCode = new String(temp).getBytes();
            if ((uniCode[0] < 128) && (uniCode[0] > 0))
                buffer.append(temp);
            else
            {
                buffer.append(convert(uniCode));
            }
        }
        return buffer.toString();
    }

    static char convert(byte[] bytes)
    {
        char result = '-';
        int secPosValue = 0;

        for (int i = 0; i < bytes.length; i++)
        {
            int tmp12_11 = i;
            bytes[tmp12_11] = ((byte) (bytes[tmp12_11] - 160));
        }
        secPosValue = bytes[0] * 100 + bytes.length;
        for (int i = 0; i < 23; i++)
        {
            if ((secPosValue >= secPosValueList[i])
                    && (secPosValue < secPosValueList[(i + 1)]))
            {
                result = firstLetter[i];
                break;
            }
        }
        return result;
    }

    public static boolean contain(String[] mArray, String m)
    {
        String[] arrayOfString = mArray;
        int j = mArray.length;
        for (int i = 0; i < j; i++)
        {
            String s = arrayOfString[i];
            if (s.equals(m))
                return true;
        }
        return false;
    }

    public static boolean contain(String[] mArray, Object m)
    {
        if (m == null)
            return false;
        return contain(mArray, m.toString());
    }

    public static String numberFormart(Number n)
    {
        if (n == null)
            return "0";
        NumberFormatter formatter = new NumberFormatter("0.##");
        return formatter.print(n, Locale.CHINA);
    }

    public static boolean checkFileUpload(String filename)
    {
        if (StringUtils.isEmpty(filename))
            return true;
        String suf = getFileSuffer(filename);
        return isInArray(suf, defaultIllegalFile);
    }

    public static boolean checkIsPic(String filename)
    {
        if (StringUtils.isEmpty(filename))
            return true;
        String suf = getFileSuffer(filename);
        return isInArrayIgnoreCase(suf, defaultIllegalPicFile);
    }

    public static boolean isImgExt(String imgExt)
    {

        return isInArrayIgnoreCase(imgExt, defaultIllegalPicFile);
    }

    public static boolean checkFileUpload(String filename, String[] illegalFile)
    {
        if (StringUtils.isEmpty(filename))
            return true;
        if ((illegalFile == null) || (illegalFile.length == 0))
            return true;
        String suf = getFileSuffer(filename);
        return isInArray(suf, illegalFile);
    }

    public static String getFileSuffer(String filename)
    {
        if (filename == null)
            return "";
        String suf = filename
                .substring(filename.lastIndexOf(".") + 1, filename.length())
                .toLowerCase();
        return suf;
    }

    public static Integer getInteger(Map map, Object key, Integer defaultValue)
    {
        Object v = map.get(key);
        if (v == null)
        {
            return defaultValue;
        }
        if ((v instanceof Integer))
            return v == null ? defaultValue : (Integer) v;
        if ((v instanceof String))
        {
            return StringUtils.isEmpty((String) v) ? defaultValue
                    : Integer.valueOf((String) v);
        }
        return defaultValue;
    }

    public static Boolean getBoolean(Map map, Object key, Boolean defaultValue)
    {
        Object v = map.get(key);
        if ((v instanceof Boolean))
            return v == null ? defaultValue : (Boolean) v;
        if ((v instanceof String))
        {
            return StringUtils.isEmpty((String) v) ? defaultValue
                    : Boolean.valueOf((String) v);
        }
        return defaultValue;
    }

    public static String getString(Map map, Object key, String defaultValue)
    {
        Object v = map.get(key);
        if ((v instanceof String))
        {
            return v == null ? defaultValue : (String) v;
        }
        return StringUtils.isEmpty((String) v) ? defaultValue : v.toString();
    }

    public static String leftGood(String str)
    {
        String s = str.replaceAll("\\*", "").replaceAll("#", "")
                .replaceAll("\\(", "").replaceAll("\\)", "").replaceAll("<", "")
                .replaceAll(">", "").replaceAll("$", "").replaceAll("%", "")
                .replaceAll("/", "");
        return s;
    }

    public static Map<String, Object> getRequestParams(
            HttpServletRequest request)
    {
        Map map = new HashMap();
        Enumeration enums = request.getParameterNames();
        while (enums.hasMoreElements())
        {
            String param = (String) enums.nextElement();
            map.put(param, request.getParameter(param));
        }
        return map;
    }

    public static Map<String, Object> getRequestAttrs(
            HttpServletRequest request)
    {
        Map map = new HashMap();
        Enumeration enums = request.getAttributeNames();
        while (enums.hasMoreElements())
        {
            String param = (String) enums.nextElement();
            map.put(param, request.getAttribute(param));
        }
        return map;
    }

    public static void printRequestHead(HttpServletRequest request)
    {
        Enumeration enums = request.getHeaderNames();
        while (enums.hasMoreElements())
        {
            String param = (String) enums.nextElement();
            log.info(param + " " + request.getHeader(param));
        }
    }

    public static boolean illegalSearchKey(String key)
    {
        return isInArray(key, illegalKeys);
    }

    public static String replaceBlank(String str)
    {
        String dest = "";
        if (str != null)
        {
            Pattern p = Pattern.compile("\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * @Title: isMobile @Description: TODO(验证手机号 ) @param @param
     *         str @param @return 设定文件 @return boolean 返回类型 @throws
     */
    public static boolean isMobile(String str)
    {
        if (null == str)
        {
            return false;
        }

        Pattern p = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * @Title: isSmsToken @Description: TODO(验证短信验证码 ) @param @param
     *         str @param @return 设定文件 @return boolean 返回类型 @throws
     */
    public static boolean isSmsToken(String str)
    {
        if (null == str)
        {
            return false;
        }

        Pattern p = Pattern.compile("^\\d{6}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static String utf8ToGBK(String str)
    {
        if (null == str)
        {
            return "";
        }

        try
        {
            return new String(str.getBytes("utf-8"), "gbk");
        }
        catch(UnsupportedEncodingException e)
        {
            log.error("convert utf-8 to gbk failed");
            return "";
        }
    }

    /**
     * @Title: floatRound
     * @Description: TODO(float四舍五入)
     * @param f
     * @param scale
     *            保留的小数位
     * @return float 返回类型
     */
    public static float floatRound(float f, int scale)
    {
        BigDecimal bd = new BigDecimal(Float.toString(f));
        bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return bd.floatValue();
    }

    public static double doubleRound(double d, int scale)
    {
        BigDecimal bd = new BigDecimal(Double.toString(d));
        bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    /**
     * @Title: getAnonymity @Description: TODO(获取匿名) @param @param
     *         str @param @return 设定文件 @return String 返回类型 @throws
     */
    public static String getAnonymity(String str)
    {
        String anonymity = "***";

        if (StringUtils.isEmpty(str))
        {
            return anonymity;
        }

        if (str.length() > 3)
        {
            anonymity = str.substring(0, 2) + anonymity
                    + str.substring(str.length() - 2);
        }
        else if (str.length() == 3)
        {
            anonymity = str.substring(0, 2) + anonymity
                    + str.substring(str.length() - 1);
        }
        else if (str.length() == 2)
        {
            anonymity = str.substring(0, 1) + anonymity
                    + str.substring(str.length() - 1);
        }
        else
        {
            anonymity = str + anonymity;
        }

        return anonymity;
    }

    public static String getAnonymityMobile(String mobile)
    {
        return mobile.substring(0, 3) + "****"
                + mobile.substring(mobile.length() - 4);
    }

    public static String getAnonymityEmail(String email)
    {
        int i = email.indexOf("@");
        return getAnonymity(email.substring(0, i)) + email.substring(i);
    }

    public static String getAnonymityName(String name)
    {
        String anonymity = name.substring(0, 1);

        for (int i = 1; i < name.length(); i++)
        {
            anonymity += "*";
        }

        return anonymity;
    }

    public static String getBankCardTailNo(String cardNo)
    {
        return cardNo.substring(cardNo.length() - 4);
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     *
     * @param nonCheckCodeCardNo
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardNo)
    {
        char[] chs = nonCheckCodeCardNo.toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++)
        {
            int k = chs[i] - '0';
            if (j % 2 == 0)
            {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    /**
     * 校验银行卡卡号
     *
     * @param cardNo
     * @return
     */
    public static boolean checkBankCardNo(String cardNo)
    {
        if (null == cardNo)
        {
            return false;
        }

        Pattern p = Pattern.compile("^[1-9][0-9]{15,18}$");
        Matcher m = p.matcher(cardNo);

        if (!m.matches())
        {
            return false;
        }

        char bit = getBankCardCheckCode(
                cardNo.substring(0, cardNo.length() - 1));
        return cardNo.charAt(cardNo.length() - 1) == bit;
    }

    public static String getImageUploadPath()
    {
        return File.separator + "upload" + File.separator + "image" + File.separator + DateUtils.format(new Date(), "yyyyMM" + File.separator+"dd") + File.separator;
    }

    /**
     * @Title: isSameDate
     * @Description: TODO(两个日期是否同一天)
     * @param @param date1
     * @param @param date2
     * @param @return 设定文件
     * @return boolean 返回类型
     * @throws
     */
    public static boolean isSameDate(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);

        boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                .get(Calendar.YEAR);
        boolean isSameMonth = isSameYear
                && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
        boolean isSameDate = isSameMonth
                && cal1.get(Calendar.DAY_OF_MONTH) == cal2
                        .get(Calendar.DAY_OF_MONTH);

        return isSameDate;
    }

    public static void main(String[] args) throws UnsupportedEncodingException
    {
        // String str =
        // "[{'cartId':3,'number':2},{'cartId':4,'number':1},{'cartId':1,'number':2},{'cartId':2,'number':2}]";
        //
        // JSONArray json = JSONArray.parseArray(str);
        // int size = json.size();
        // for(int i = 0; i<size; i++)
        // {
        // String re = json.getString(i);
        // JSONObject s = JSONObject.parseObject(re);
        // System.out.println(s.getInteger("cartId"));
        // System.out.println(s.getInteger("number") + "\n");
        // }
        System.out.println(getImageUploadPath());
    }
}
